package jxau.jwgl.service.impl;

import jxau.jwgl.api.ChooseCourseApi;
import jxau.jwgl.api.JWGLServerException;
import jxau.jwgl.api.MessageData;
import jxau.jwgl.api.WebApiFactory;
import jxau.jwgl.commons.entity.Course;
import jxau.jwgl.commons.entity.CourseCategory;
import jxau.jwgl.service.ChooseCourseSerivce;
import jxau.jwgl.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import retrofit2.Response;

import java.io.IOException;
import java.util.List;

/**
 * ChooseCourseSerivceImpl
 *
 * @author LongShu 2017/06/12
 */
@Service
public class ChooseCourseSerivceImpl implements ChooseCourseSerivce {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private ChooseCourseApi chooseCourseApi = WebApiFactory.get(ChooseCourseApi.class);

    @Autowired
    private UserService userService;

    @Override
    @Cacheable(cacheNames = "course", key = "'courseInfo'+#category.id")
    public List<Course> courseInfo(String username, CourseCategory category) throws JWGLServerException {
        String guid = userService.getGuid(username);
        Integer start = category.getStart();
        Integer limit = category.getLimit();

        if (start == null || start < 0) {
            start = 0;
        }
        if (limit == null || limit < 1) {
            limit = 200;
        }

        try {
            Response<MessageData<Course>> response = chooseCourseApi.courseInfo(guid, category.getId(), start, limit).execute();
            MessageData<Course> messageData = response.body();
            return messageData.getData();
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            throw new JWGLServerException("教务系统错误,获取评教列表失败!");
        }
    }

    @Override
    @CacheEvict(cacheNames = "course", key = "'courseInfo'+#course.Xklb")
    public String chooseCourse(String username, Course course) throws JWGLServerException {
        String guid = userService.getGuid(username);
        try {
            Response<MessageData<String>> response = chooseCourseApi.chooseCourse(guid, course.getXklb(), course.getJxbBh(), course.getXkpc()).execute();
            MessageData<String> messageData = response.body();
            return messageData.getMessage();
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            throw new JWGLServerException("教务系统错误,选课失败!");
        }
    }

}
